package com.example.hosptial.newController;

import com.example.hosptial.model.enity.Patient;
import com.example.hosptial.model.view.DoctorView;
import com.example.hosptial.model.view.WardBedPatientView;
import com.example.hosptial.model.view.WardStatusView;
import com.example.hosptial.service.AdmissionService;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

/**
 * 住院管理控制器
 */
@Controller
@RequestMapping("/doctor/admission")
public class AdmissionController {

    private static final Logger logger = LoggerFactory.getLogger(AdmissionController.class);

    @Autowired
    private AdmissionService admissionService;

    /**
     * 显示入院管理主页面
     */
    @GetMapping
    public String showAdmissionPage(HttpSession session, Model model) {
        DoctorView doctor = (DoctorView) session.getAttribute("doctor");
        if (doctor == null) {
            return "redirect:/doctor/auth/login";
        }
        return "doctor/admission";
    }

    /**
     * 获取楼层列表
     */
    @GetMapping("/floors")
    @ResponseBody
    public ResponseEntity<List<Integer>> getFloors(HttpSession session) {
        DoctorView doctor = (DoctorView) session.getAttribute("doctor");
        if (doctor == null) {
            return ResponseEntity.status(401).build();
        }
        try {
            logger.info("获取科室 {} 的楼层列表", doctor.getDeptId());
            List<Integer> floors = admissionService.getFloorsByDepartment(doctor.getDeptId());
            logger.info("找到 {} 个楼层", floors.size());
            return ResponseEntity.ok(floors);
        } catch (Exception e) {
            logger.error("获取楼层列表失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取指定楼层的病房列表
     */
    @GetMapping("/wards")
    @ResponseBody
    public ResponseEntity<List<Map<String, Object>>> getWards(
            @RequestParam Integer floorNum,
            HttpSession session) {
        DoctorView doctor = (DoctorView) session.getAttribute("doctor");
        if (doctor == null) {
            return ResponseEntity.status(401).build();
        }
        try {
            logger.info("获取楼层 {} 的病房列表", floorNum);
            List<WardStatusView> wards = admissionService.getAvailableWardsByFloorAndDept(doctor.getDeptId(), floorNum);
            
            // 转换为前端需要的格式
            List<Map<String, Object>> response = wards.stream()
                .map(ward -> {
                    Map<String, Object> wardMap = new HashMap<>();
                    wardMap.put("wardId", ward.getWardId());
                    wardMap.put("wardNum", ward.getWardNum());
                    wardMap.put("availableBeds", ward.getAvailableBeds());
                    return wardMap;
                })
                .collect(Collectors.toList());
            
            logger.info("找到 {} 个可用病房", response.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取病房列表失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取指定病房的可用床位
     */
    @GetMapping("/beds")
    @ResponseBody
    public ResponseEntity<List<Map<String, Object>>> getBeds(
            @RequestParam Integer wardId,
            HttpSession session) {
        DoctorView doctor = (DoctorView) session.getAttribute("doctor");
        if (doctor == null) {
            return ResponseEntity.status(401).build();
        }
        try {
            logger.info("获取病房 {} 的床位列表", wardId);
            List<WardBedPatientView> beds = admissionService.getAvailableBedsByWard(wardId);
            
            // 转换为前端需要的格式
            List<Map<String, Object>> response = beds.stream()
                .map(bed -> {
                    Map<String, Object> bedMap = new HashMap<>();
                    bedMap.put("bedId", bed.getBedId());
                    bedMap.put("bedNum", bed.getBedNum());
                    return bedMap;
                })
                .collect(Collectors.toList());
            
            logger.info("找到 {} 个可用床位", response.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取床位列表失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 处理入院申请
     */
    @PostMapping
    @ResponseBody
    public ResponseEntity<?> admitPatient(
            @Valid Patient patient,
            BindingResult bindingResult,
            @RequestParam Integer bedId,
            HttpSession session) {
        
        DoctorView doctor = (DoctorView) session.getAttribute("doctor");
        if (doctor == null) {
            return ResponseEntity.status(401).body(Map.of(
                "error", "未登录或会话已过期"
            ));
        }

        // 验证参数
        if (bindingResult.hasErrors()) {
            Map<String, String> errors = bindingResult.getFieldErrors().stream()
                .collect(Collectors.toMap(
                    FieldError::getField,
                    FieldError::getDefaultMessage,
                    (msg1, msg2) -> msg1
                ));
            return ResponseEntity.badRequest().body(Map.of(
                "error", "参数验证失败",
                "details", errors
            ));
        }

        try {
            logger.info("处理病人 {} 的入院申请", patient.getPatientName());
            admissionService.admitPatient(
                patient.getPatientName(),
                patient.getPatientGender(),
                patient.getPatientAge(),
                patient.getPatientIdCard(),
                patient.getPatientPhone(),
                patient.getConditionDesc(),
                doctor.getDoctorId(),
                bedId
            );
            
            logger.info("病人 {} 入院办理成功", patient.getPatientName());
            return ResponseEntity.ok(Map.of(
                "message", "入院办理成功"
            ));
        } catch (IllegalArgumentException e) {
            logger.warn("入院办理失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(Map.of(
                "error", e.getMessage()
            ));
        } catch (Exception e) {
            logger.error("入院办理失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body(Map.of(
                "error", "入院办理失败，请稍后重试"
            ));
        }
    }
}